import { useApiSettings } from '../contexts/ApiSettingsContext';

// 表示文本嵌入的接口
export interface TextEmbedding {
  text: string;
  embedding: number[];
}

// Embedding请求接口
export interface EmbeddingRequest {
  texts: string[];
  model?: string;
  dimensions?: number;
  normalize?: boolean;
}

// Embedding服务接口
export class EmbeddingService {
  private apiSettings;

  constructor() {
    const { apiSettings } = useApiSettings();
    this.apiSettings = apiSettings.embedding;
  }

  // 创建文本嵌入
  async createEmbeddings(request: EmbeddingRequest): Promise<TextEmbedding[]> {
    const { texts, model, dimensions, normalize } = request;
    
    // 使用设置中的默认值
    const embeddingModel = model || this.apiSettings.model;
    const embeddingDimensions = dimensions || this.apiSettings.dimensions;
    const shouldNormalize = normalize !== undefined ? normalize : this.apiSettings.normalize;
    
    try {
      // 实际项目中应该发起API请求
      // 这里使用模拟数据
      const batchSize = this.apiSettings.batchSize;
      const results: TextEmbedding[] = [];
      
      // 按批次处理
      for (let i = 0; i < texts.length; i += batchSize) {
        const batch = texts.slice(i, i + batchSize);
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 300 + Math.random() * 500));
        
        // 为每个文本生成模拟嵌入向量
        for (const text of batch) {
          // 生成指定维度的随机向量
          const embedding = Array.from(
            { length: embeddingDimensions }, 
            () => Math.random() * 2 - 1
          );
          
          // 如果需要归一化
          if (shouldNormalize) {
            const magnitude = Math.sqrt(
              embedding.reduce((sum, val) => sum + val * val, 0)
            );
            
            if (magnitude > 0) {
              for (let j = 0; j < embedding.length; j++) {
                embedding[j] /= magnitude;
              }
            }
          }
          
          results.push({ text, embedding });
        }
      }
      
      return results;
    } catch (error) {
      console.error('Error creating embeddings:', error);
      throw new Error('Failed to create embeddings');
    }
  }

  // 单个文本嵌入的便捷方法
  async embedText(text: string): Promise<number[]> {
    const results = await this.createEmbeddings({ texts: [text] });
    return results[0].embedding;
  }
} 